import json
import os

def save_to_file(items, filename="data/items.json"):
    """Save project list to JSON document"""
    try:
        os.makedirs(os.path.dirname(filename), exist_ok=True)
        
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(items, f, ensure_ascii=False, indent=2)
        print(f"✅ Data has saved to: {filename}")
        return True
    except Exception as e:
        print(f"❌ Error occurred while saving the file: {e}")
        return False

def load_from_file(filename="data/items.json"):
    """Load project list from JSON document"""
    try:
        if not os.path.exists(filename):
            print("📁 Data document does not exist, create a new document")
            return []
        
        with open(filename, 'r', encoding='utf-8') as f:
            items = json.load(f)
        print(f"✅ 从 {filename} Data loading success")
        return items
    except Exception as e:
        print(f"❌ Error occurred while loading the file: {e}")
        return []

def backup_data(items, backup_dir="data/backups"):
    """Create data backup"""
    import datetime
    try:
        os.makedirs(backup_dir, exist_ok=True)
        timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
        backup_file = os.path.join(backup_dir, f"backup_{timestamp}.json")
        save_to_file(items, backup_file)
        print(f"✅ backup has created: {backup_file}")
        return True
    except Exception as e:
        print(f"❌ backup fails: {e}")
        return False